/**
 * 
 */
package com.yi.role.internal.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.util.StringUtils;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.yi.model.db.mongo.MongoDBHelper;
import com.yi.model.internal.impl.ModelApi;
import com.yi.model.objects.DBDefinitions;
import com.yi.role.internal.IRoleApi;
import com.yi.role.objects.Role;

/**
 * @author long
 *
 */
public class RoleApi extends ModelApi implements IRoleApi {

	private MongoDBHelper dbHelper;
	
	public boolean checkAccessRight(final String roleId, final String objName, final String operName){
	
		return dbHelper.checkAccessRight(DBDefinitions.roleColl, roleId, objName, operName);
	}
	/* (non-Javadoc)
	 * @see com.yi.role.internal.IRoleApi#create(com.yi.role.objects.Role)
	 */
	public String create(Role role) {
		// TODO Auto-generated method stub
		return dbHelper.addEntity(DBDefinitions.roleColl, convertRoleToEntity(role));
	}

	/* (non-Javadoc)
	 * @see com.yi.role.internal.IRoleApi#view(java.lang.String)
	 */
	public Role view(String id) {
		// TODO Auto-generated method stub
		return convertEntityToRole(dbHelper.viewEntityById(DBDefinitions.roleColl, id));
	}

	/* (non-Javadoc)
	 * @see com.yi.role.internal.IRoleApi#update(com.yi.role.objects.Role)
	 */
	public void update(Role role) {
		// TODO Auto-generated method stub
		dbHelper.updateEntity(DBDefinitions.roleColl,convertRoleToEntity(role));
	}

	/* (non-Javadoc)
	 * @see com.yi.role.internal.IRoleApi#delete(java.lang.String)
	 */
	public void delete(String id) {
		// TODO Auto-generated method stub
		dbHelper.removeEntityById(DBDefinitions.roleColl, id);
	}

	/* (non-Javadoc)
	 * @see com.yi.role.internal.IRoleApi#list()
	 */
	public List<Role> list(int pageNumber) {
		// TODO Auto-generated method stub
		List<DBObject> matches = dbHelper.findEntities(DBDefinitions.roleColl, pageNumber);
		List<Role> roles = new ArrayList<Role>();
		for(DBObject entity : matches){
			roles.add(convertEntityToRole(entity));
		}
		return roles;
	}

	private DBObject convertRoleToEntity(Role role){
		DBObject entity = convertModelToEntity(role);
		if((role.permissions.size() > 0))  entity.put(DBDefinitions.col_permission, role.permissions);		
		return entity;
	}
	
	private Role convertEntityToRole(DBObject entity){
		Role role = new Role(convertEntityToModel(entity));
		role.permissions = ((Map<String,String>)entity.get(DBDefinitions.col_permission));
		return role;
	}

	public MongoDBHelper getDbHelper() {
		return dbHelper;
	}

	public void setDbHelper(MongoDBHelper dbHelper) {
		this.dbHelper = dbHelper;
	}
}
